<template>
  <div class="main-materialClassification">
    <div style="display:flex; padding: 15px 0; border-bottom: 1px solid #fff;">
      <div style="width:33%; text-align: center; ">
        <label class="btn btn-primary" style="margin: 3px 0; ">
          <input class="cz-pipeline-type" type="checkbox" value="ZY_JSLINE"> 给水线
        </label>
        <br/>
        <label class="btn btn-primary" style="margin: 3px 0; ">
          <input class="cz-pipeline-type" type="checkbox" value="ZY_YSLINE"> 雨水线
        </label>
        <br/>
        <label class="btn btn-primary" style="margin: 3px 0; ">
          <input class="cz-pipeline-type" type="checkbox" value="ZY_GDLINE"> 电力线
        </label>
        <br/>
        <label class="btn btn-primary" style="margin: 3px 0; ">
          <input class="cz-pipeline-type" type="checkbox" value="ZY_LDLINE"> 路灯线
        </label>
      </div>
      <div style="width:33%; text-align: center; ">
        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                @click="allSelect(1)">全选
        </button>
        <br/>
        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                @click="allSelect(-1)">全不选
        </button>
        <br/>
        <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                @click="allSelect(0)">反选
        </button>
      </div>

    </div>
    <div class="layui-row" style="padding: 15px 0; border-bottom: 1px solid #fff;">
      <div class="layui-col-md3 layui-col-md-offset1">
        <label class="btn btn-primary">
          <input type="checkbox" id="spatial"> 空间范围
        </label>
      </div>
      <div class="layui-col-md6">
        <input type="button" class="btn btn-primary" value="矩形" @click="drawRectangle"/>
        <input type="button" class="btn btn-primary" value="面" @click="drawPolygon"/>
        <input type="button" class="btn btn-primary" value="圆" @click="drawCircle"/>
        <input type="button" class="btn btn-primary" value="清除" @click="clearDraw"/>
      </div>
    </div>
    <div class="layui-row">
      <div class="layui-col-md6 layui-col-md-offset1">
        <button type="button" class="layui-btn " style="margin: 3px 0; width: 120px;" @click="flhz">
          分类汇总
        </button> &nbsp;&nbsp;
        <button type="button" class="layui-btn " style="margin: 3px 0; width: 120px;" @click="qc">清除
        </button> &nbsp;&nbsp;
      </div>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
import clearWindow from "@/components/js/clearWindow";

let from
// eslint-disable-next-line no-unused-vars
let dataTable = []
let openlayerTable = null
let $table

import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import statistics from "@/components/js/statistics";

export default {
  name: "materialClassification",
  components: {},
  data() {
    return {};
  },
  mounted() {

  },
  methods: {
    qc() {
      this.clearDraw()
      this.allSelect(-1)
      openlayerTable && layui.layer.close(openlayerTable)
      openlayerTable = null
      if ($('#spatial')[0]) $('#spatial')[0].checked = false
    },
    hideLayerContent() {
      this.$emit('hidden')
    },
    showLayerContent() {
      this.$emit('show')
    },
    clearDraw() {
      window.viewer.dadi.draw.clearDraw();
      from = null;
      // $table.bootstrapTable('destroy')
      $('#layerSelect').html('');
      // $('#thead').html('')
      dataTable = []
    },
    allSelect(flag) {
      let els = $('.cz-pipeline-type')
      if (flag == 1) {
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = true
        }
      } else if (flag == -1) {
        $('.cz-pipeline-type').attr('checked', false)
      } else { // 反选
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = !element.checked
        }
      }
    },
    drawRectangle() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "rectangle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.showLayerContent()
        }
      });
    },
    drawPolygon() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "polygon",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.showLayerContent()
        }
      });
    },
    drawCircle() {
      this.clearDraw();
      this.hideLayerContent()
      window.viewer.dadi.draw.startDraw({
        type: "circle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: () => {
          this.showLayerContent()
        }
      });
    },
    flhz() {
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()
      let els = $('.cz-pipeline-type')
      let pipelineTypes = []
      for (let index = 0; index < els.length; index++) {
        const element = els[index];
        if (element.checked) {
          pipelineTypes.push(element.value)
        }
      }

      if (pipelineTypes.length == 0) {
        layui.layer.alert('至少选择一类管线进行统计！')
        return;
      }

      if ($('#spatial')[0].checked && !drawGeojson) {
        layui.layer.alert('空间统计请绘制范围！')
        return;
      }

      // 求from
      if ($('#spatial')[0].checked && drawGeojson) {
        if (drawGeojson.features[0].properties.type === 'circle') {
          from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
        } else if (drawGeojson.features[0].properties.type === 'polygon') {
          from = turf.feature(drawGeojson.features[0].geometry)
        } else if (drawGeojson.features[0].properties.type === 'rectangle') {
          let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
            a.splice(-1)
            b.splice(-1)
            return a.concat(b)
          })
          from = turf.bboxPolygon(geo)
        }
      }

      let bianli = 0;
      let tableArr = [];
      pipelineTypes.forEach(async item => {
        bianli++;
        let properties = [];
        let mylayer = layersMap.find(l => l.pipelineType === item)

        const r = await fetchData(mylayer.url)
        r.features.forEach(fea => {
          // 空间筛选
          if ($('#spatial')[0].checked && drawGeojson) {

            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, from);
            if (withIntersect) {
              properties.push(fea.properties)
            }
          } else {
            properties.push(fea.properties)
          }
        })

        let res = statistics(properties, '材质', 'SHAPE_Leng')
        let sumCount = 0, sumSum = 0;
        Object.keys(res).forEach(k => {
          sumCount += res[k].count
          sumSum += res[k].sum
          let dh = ''
          if (mylayer.pipelineType.indexOf('POINT') > -1) {
            dh = mylayer.pipelineType.split('_')[1].split('POINT')[0]
          } else {
            dh = mylayer.pipelineType.split('_')[1].split('LINE')[0]
          }
          tableArr.push({
            '层名':mylayer.type, '要素代号' : dh, '材质': k, '条数': res[k].count,'长度': res[k].sum , '总条数': '', '总长度': '',
          })
        })
        // 汇总
        tableArr.push({
          '层名': mylayer.type,
          '材质': '',
          '条数': '',
          '长度': '',
          '总条数': '合计：' + sumCount + '条',
          '总长度': '合计：' + sumSum.toFixed(3) + '米',
        })
      })

      function refreshTable(tableArr) {
        $table = $('#table');
        let thead = `<tr>`
        Object.keys(tableArr[0]).forEach(key => {
          thead += `<th data-field="${key}">${key}</th>`
        })
        thead += `</tr>`
        $table.bootstrapTable('destroy')
        $('#thead').html(thead)
        $table.bootstrapTable({
          data: tableArr,
          // eslint-disable-next-line no-unused-vars
          onClickRow: function (row, $element) {

          }
        })
        $table.bootstrapTable('refresh')
      }

      let timer = setInterval(() => {
        if (bianli === pipelineTypes.length) {
          window.clearInterval(timer)
          if (openlayerTable) {
            refreshTable(tableArr)
          } else {
            openlayerTable = layui.layer.open({
              type: 1,
              area: ['800px', '620px'], // 宽高
              title: "分类汇总表", // 不显示标题栏
              offset: ['100px', '650px'],
              closeBtn: 1,
              shade: false,
              shadeClose: false,
              content: `
                        <table
                            id="table"
                            data-toggle="table"
                            data-height="550"
                            data-width="430"
                            data-search="true"
                            data-pagination="true"
                            style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
                            >
                            <thead id="thead" style="color:#fff;">

                            </thead>
                        </table>
                        `,
              // eslint-disable-next-line no-unused-vars
              cancel: function (index, layero, that) {
                openlayerTable = null;
                layui.layer.close(index);
                return false; // 阻止默认关闭行为
              },
              // eslint-disable-next-line no-unused-vars
              success: function (layero, index) {
                refreshTable(tableArr)
              }
            })
          }
        }
      }, 2000);

    },

  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    clearWindow()
  },
}
</script>

<style scoped>
.main-materialClassification {
  position: relative;
  height: 100%;
  width: 100%;
}
</style>
<style>
.main-materialClassification > div:nth-child(1),.main-materialClassification > div:nth-child(2){
  border-bottom: 1px solid #0aa8e4!important;
}
.main-materialClassification > div:nth-child(3) button {
  background-image: url("../assets/img/button/button.png");
  background-size: 100% 100%;
  background-color: transparent!important;
}

</style>